<template>
    <div class="gateway-restart">
        <a-card title="网关重启" :bordered="false">
            <div class="restart-section">
                <p class="description">重启网关设备可能需要几分钟时间，请耐心等待。</p>
                <a-button 
                    type="primary" 
                    :loading="restarting" 
                    :disabled="restarting"
                    @click="confirmRestart"
                >
                    {{ restarting ? '正在重启...' : '重启网关' }}
                </a-button>
            </div>

            <!-- 重启历史记录 -->
            <div class="history-section">
                <h3>重启历史</h3>
                <a-list 
                    :data-source="restartHistory" 
                    :locale="{ emptyText: '暂无重启记录' }"
                >
                    <a-list-item slot="renderItem" slot-scope="item">
                        <a-list-item-meta>
                            <div slot="title">
                                {{ item.gateway }}
                                <a-tag :color="item.status === 'success' ? 'green' : 'red'">
                                    {{ item.status === 'success' ? '成功' : '失败' }}
                                </a-tag>
                            </div>
                            <div slot="description">{{ item.time }}</div>
                        </a-list-item-meta>
                    </a-list-item>
                </a-list>
            </div>
        </a-card>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import DeviceTabManager from '@/api/TabManager/DeviceTabManager'
import { GATEWAY_CONFIGS } from '@/config/gateway-config'

export default {
    name: 'GatewayRestart',
    props: {
        ipAddress: {
            type: String,
            required: true
        },
        port: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            restarting: false,
            restartHistory: [],
            deviceTabManager: new DeviceTabManager(),
            statusCheckTimer: null
        }
    },
    computed: {
        ...mapGetters('groupTree', ['selectedDeviceInfo']),
        // 获取当前设备的更新模式
        currentDeviceUpdateMode() {
            if (!this.selectedDeviceInfo) {
                return 'ethernet' // 默认为网络模式
            }

            // 如果直接有updateMode属性，使用它
            if (this.selectedDeviceInfo.updateMode) {
                return this.selectedDeviceInfo.updateMode
            }

            // 根据设备类型获取updateMode
            const deviceType = this.selectedDeviceInfo.gatewayType || this.selectedDeviceInfo.deviceType
            const config = GATEWAY_CONFIGS[deviceType]
            
            if (config && config.hardwareInfo && config.hardwareInfo.updateMode) {
                return config.hardwareInfo.updateMode
            }

            return 'ethernet' // 默认为网络模式
        }
    },
    beforeDestroy() {
        this.clearStatusCheck()
    },
    methods: {
        // 确认重启
        confirmRestart() {
            // 需要判断是不是网口设备
            if (this.currentDeviceUpdateMode !== 'ethernet') {
                this.$message.error('网口设备才能重启')
                return
            }            
            this.$confirm({
                title: '确认重启',
                content: '确定要重启网关设备吗？重启过程可能需要几分钟时间。',
                okText: '确定重启',
                cancelText: '取消',
                type: 'warning',
                onOk: () => {
                    this.startRestart()
                }
            })
        },
        
        // 开始重启
        async startRestart() {
            if (!this.selectedDeviceInfo) {
                this.$message.error('请先选择设备')
                return
            }

            // 验证网络参数
            if (!this.ipAddress || !this.ipAddress.trim()) {
                this.$message.error('请先输入IP地址')
                return
            }

            if (!this.port || !this.port.trim()) {
                this.$message.error('请先输入端口号')
                return
            }

            try {
                this.restarting = true
                
                // 获取IP和端口参数
                const data = {
                    ip: this.ipAddress.trim(),
                    port: this.port.trim()
                }
                
                console.log('🔄 [GatewayRestart] 开始重启网关:', data)
                const response = await this.deviceTabManager.restartGateway(JSON.stringify(data))
                
                if (response.code === 0) {
                    this.$message.info('重启指令已发送，正在等待设备重启...')
                    // this.startStatusCheck()
                } else {
                    this.handleRestartFailure('重启指令发送失败: ' + response.msg)
                }
                this.restarting = false
            } catch (error) {
                this.handleRestartFailure('重启失败: ' + error.message)
                this.restarting = false
            }
        },
        
        // 开始状态检查
        startStatusCheck() {
            // 清除可能存在的旧定时器
            this.clearStatusCheck()
            
            // 创建新的状态检查定时器
            this.statusCheckTimer = setInterval(async() => {
                try {
                    const params = {
                        ip: this.ipAddress,
                        port: this.port
                    }
                    
                    const response = await this.deviceTabManager.getGatewayRestartStatus(JSON.stringify(params))
                    
                    if (response.code === 0) {
                        const status = response.data
                        
                        if (status.completed) {
                            // 重启完成
                            this.handleRestartComplete(status.success)
                        }
                    }
                } catch (error) {
                    console.error('❌ [GatewayRestart] 获取重启状态失败:', error)
                }
            }, 2000) // 每2秒检查一次
            
            // 设置超时保护
            setTimeout(() => {
                if (this.restarting) {
                    this.handleRestartFailure('重启超时，请检查设备状态')
                }
            }, 10 * 1000) // 10秒钟超时
        },
        
        // 清除状态检查
        clearStatusCheck() {
            if (this.statusCheckTimer) {
                clearInterval(this.statusCheckTimer)
                this.statusCheckTimer = null
            }
        },
        
        // 处理重启完成
        handleRestartComplete(success) {
            this.clearStatusCheck()
            this.restarting = false
            
            const message = success ? '网关重启成功' : '网关重启失败'
            this.$message[success ? 'success' : 'error'](message)
            
            // 更新重启历史
            this.restartHistory.unshift({
                gateway: this.selectedDeviceInfo?.name || '未知设备',
                time: new Date().toLocaleString(),
                status: success ? 'success' : 'failed'
            })
        },
        
        // 处理重启失败
        handleRestartFailure(errorMessage) {
            this.clearStatusCheck()
            this.restarting = false
            this.$message.error(errorMessage)
            
            // 更新重启历史
            this.restartHistory.unshift({
                gateway: this.selectedDeviceInfo?.name || '未知设备',
                time: new Date().toLocaleString(),
                status: 'failed'
            })
        }
    }
}
</script>

<style scoped>
.gateway-restart {
    padding: 20px;
}
.restart-section {
    text-align: center;
    margin-bottom: 30px;
}
.description {
    margin-bottom: 20px;
    color: #666;
}
.history-section {
    margin-top: 30px;
}
.history-section h3 {
    margin-bottom: 16px;
    color: rgba(0, 0, 0, 0.85);
    font-weight: 500;
}
:deep(.ant-list-item-meta-title) {
    margin-bottom: 4px;
}
:deep(.ant-list-item-meta-description) {
    color: rgba(0, 0, 0, 0.45);
}
:deep(.ant-tag) {
    margin-left: 8px;
}
</style> 